# -*- coding: utf-8 -*-
"""
带状态按钮通用类模块
实现可以通过setProperty和property管理状态的按钮
"""

from PySide2.QtWidgets import QPushButton
from PySide2.QtCore import Qt, Signal, QStateMachine, QState, QPropertyAnimation, QEasingCurve
from PySide2.QtGui import QFont
from gglobal import logger
from ..handlercore.language_manager import LanguageManager


class PropertyButton(QPushButton):
    """带状态管理的按钮类
    
    支持通过setProperty和property方法管理按钮状态
    可以设置不同状态下的文本、样式等
    """
    
    # 状态改变信号
    state_changed = Signal(str)  # 发送新状态名称
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self._states = {}  # 存储状态配置
        self._current_state = None
        self._use_state_machine = False
        self._state_machine = None
        self._state_objects = {}
        self.language_manager = LanguageManager()  # 多语言管理器
        
        # 设置默认属性
        self.setObjectName("property_button")

        # 监听语言切换，实时刷新当前状态文本
        try:
            self.language_manager.language_changed.connect(self._on_language_changed)
        except Exception as e:
            logger.warning(f"语言管理器连接失败: {e}")
        
    def add_state(self, state_name, text=None, enabled=True, style_class=None, use_state_machine=False, text_key=None):
        """添加状态配置
        
        参数:
            state_name: 状态名称
            text: 状态对应的按钮文本
            enabled: 状态下按钮是否可用
            style_class: 状态对应的样式类名（用于CSS选择器）
            use_state_machine: 是否使用状态机管理
            text_key: 文本键（用于多语言获取），若提供则优先使用语言资源
        """
        self._states[state_name] = {
            'text': text or state_name,
            'enabled': enabled,
            'style_class': style_class,
            'text_key': text_key
        }
        
        if use_state_machine and not self._use_state_machine:
            self._use_state_machine = True
            self._setup_state_machine()
            
        logger.debug(f"添加状态: {state_name}, 文本: {text}, 启用: {enabled}")
        
    def _setup_state_machine(self):
        """设置状态机"""
        if self._state_machine:
            return
            
        self._state_machine = QStateMachine(self)
        
        # 为每个状态创建QState对象
        for state_name in self._states.keys():
            state_obj = QState(self._state_machine)
            state_obj.setObjectName(state_name)
            self._state_objects[state_name] = state_obj
            
            # 状态进入时的处理
            state_obj.entered.connect(lambda name=state_name: self._on_state_entered(name))
            
        # 设置初始状态
        if self._state_objects:
            first_state = list(self._state_objects.values())[0]
            self._state_machine.setInitialState(first_state)
            
        self._state_machine.start()
        logger.debug("状态机设置完成")
        
    def _on_state_entered(self, state_name):
        """状态进入时的处理"""
        self._apply_state(state_name)
        
    def set_state(self, state_name):
        """设置当前状态
        
        参数:
            state_name: 要设置的状态名称
        """
        if state_name not in self._states:
            logger.warning(f"未知状态: {state_name}")
            return
            
        old_state = self._current_state
        self._current_state = state_name
        
        if self._use_state_machine and self._state_machine:
            # 使用状态机切换
            target_state = self._state_objects.get(state_name)
            if target_state:
                self._state_machine.setInitialState(target_state)
        else:
            # 直接应用状态
            self._apply_state(state_name)
            
        # 发送状态改变信号
        if old_state != state_name:
            self.state_changed.emit(state_name)
            
        logger.debug(f"状态切换: {old_state} -> {state_name}")
        
    def _apply_state(self, state_name):
        """应用状态配置"""
        if state_name not in self._states:
            return
            
        state_config = self._states[state_name]
        
        # 设置文本（优先使用语言键）
        try:
            text_key = state_config.get('text_key')
            if text_key:
                # 从语言资源获取文本，默认值回退到配置文本
                localized = self.language_manager.get_text(text_key, state_config.get('text') or state_name)
                if localized:
                    self.setText(localized)
                else:
                    self.setText(state_config.get('text') or state_name)
            else:
                if state_config.get('text'):
                    self.setText(state_config['text'])
        except Exception as e:
            logger.warning(f"应用状态文本失败: {state_name}, 错误: {e}")
        
        # 设置启用状态
        self.setEnabled(state_config['enabled'])
        
        # 设置样式类属性
        if state_config['style_class']:
            self.setProperty('state', state_config['style_class'])
        else:
            self.setProperty('state', state_name)
        
        # 刷新样式
        self.style().unpolish(self)
        self.style().polish(self)
        self.update()

    def _on_language_changed(self, _language_data):
        """语言切换时刷新当前状态文本"""
        try:
            if self._current_state:
                self._apply_state(self._current_state)
        except Exception as e:
            logger.warning(f"语言切换刷新失败: {e}")
        
    def get_current_state(self):
        """获取当前状态名称"""
        return self._current_state
        
    def get_states(self):
        """获取所有状态列表"""
        return list(self._states.keys())
        
    def is_in_state(self, state_name):
        """检查是否处于指定状态"""
        return self._current_state == state_name
        
    def add_state_transition(self, from_state, to_state, signal=None):
        """添加状态转换（仅在使用状态机时有效）
        
        参数:
            from_state: 源状态名称
            to_state: 目标状态名称  
            signal: 触发转换的信号（如果为None则使用clicked信号）
        """
        if not self._use_state_machine or not self._state_machine:
            logger.warning("未启用状态机，无法添加状态转换")
            return
            
        from_state_obj = self._state_objects.get(from_state)
        to_state_obj = self._state_objects.get(to_state)
        
        if not from_state_obj or not to_state_obj:
            logger.warning(f"状态转换失败: {from_state} -> {to_state}，状态不存在")
            return
            
        # 默认使用clicked信号
        if signal is None:
            signal = self.clicked
            
        transition = from_state_obj.addTransition(signal, to_state_obj)
        logger.debug(f"添加状态转换: {from_state} -> {to_state}")
        return transition


class ScanButton(PropertyButton):
    """扫描按钮类
    
    预定义扫描和扫描中两个状态
    """
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("scan_button")
        
        # 添加预定义状态
        # 文本使用语言键，避免硬编码
        self.add_state('scan', None, True, 'scan', text_key='scan_button')
        self.add_state('scanning', None, False, 'scanning', text_key='scanning_text')
        
        # 设置初始状态
        self.set_state('scan')
        
    def start_scan(self):
        """开始扫描"""
        self.set_state('scanning')
        
    def stop_scan(self):
        """停止扫描"""
        self.set_state('scan')
        

class ConnectButton(PropertyButton):
    """连接按钮类
    
    预定义连接、连接中、断开三个状态
    """
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("connect_button")
        
        # 添加预定义状态
        # 文本使用语言键，避免硬编码
        self.add_state('connect', None, True, 'connect', text_key='connect_button')
        self.add_state('connecting', None, False, 'connecting', text_key='connect_button_connecting')
        self.add_state('disconnect', None, True, 'disconnect', text_key='disconnect_button')
        
        # 设置初始状态
        self.set_state('connect')
        
    def start_connect(self):
        """开始连接"""
        self.set_state('connecting')
        
    def connected(self):
        """连接成功"""
        self.set_state('disconnect')
        
    def disconnected(self):
        """断开连接"""
        self.set_state('connect')